package priv.dajie.tzzq.spider.dota.buff;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import priv.dajie.tzzq.bot.BotManager;
import priv.dajie.tzzq.bot.buff.BuffUser;
import priv.dajie.tzzq.bot.exception.NetworkException;
import priv.dajie.tzzq.common.ApplicationContextUnit;
import priv.dajie.tzzq.model.QualityName;
import priv.dajie.tzzq.proxy.Proxy;
import priv.dajie.tzzq.service.impl.BuffServiceImpl;
import priv.dajie.tzzq.spider.Base.DotaSpider;
import priv.dajie.tzzq.spider.model.*;
import priv.dajie.tzzq.common.Tools;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class BuffDotaSpider implements Runnable, DotaSpider {

    private SpiderInfo spiderInfo;
    private BuffServiceImpl buffService;
    private BuffUser buffUser;
    private boolean useProxy;
    private Proxy proxy = null;
    // 0 插入普通表，1 插入pro表
    private SpiderMode mode;
    private Logger logger = LogManager.getLogger(this.getClass().getName());


    public BuffDotaSpider(SpiderInfo spiderInfo, BuffUser buffUser, SpiderMode mode, Proxy proxy) {
        this.spiderInfo = spiderInfo;
        this.buffUser = buffUser;
        this.buffService = (BuffServiceImpl) ApplicationContextUnit.getInstance().getBean("buffService");
        this.mode = mode;
        this.proxy = proxy;
        if (proxy!=null){
            useProxy = true;
        }
    }

    public BuffDotaSpider(BuffUser buffUser, SpiderMode mode){ // mode 0插入新表，mode 1插入旧表
        this(null, buffUser, mode, null);
    }

    public BuffDotaSpider(BuffUser buffUser, SpiderMode mode, Proxy proxy){
        this(null, buffUser, mode, proxy);
    }

    public BuffDotaSpider(SpiderMode mode, Proxy proxy){
        this(null, BotManager.getBuffSpdierBot().getBuffUser(), mode, proxy);
    }

    public BuffDotaSpider(SpiderMode mode){
        this(null, BotManager.getBuffSpdierBot().getBuffUser(), mode, null);
    }

    @Override
    public void setSpiderInfo(SpiderInfo spiderInfo) {
        this.spiderInfo = spiderInfo;
    }

    @Override
    public void startSpider(){
        String hero = null;
        String type = null;
//        buffService.setDate(new Date());
        while (true) {
            InfoElement infoElement = spiderInfo.getInfoElement();
            if(infoElement!=null){
                if(infoElement.getElementType() == ElementType.HERO){
                    hero = infoElement.getName();
                    type = null;
                }
                else {
                    type = infoElement.getName();
                    hero = null;
                }
            }
            else {
                break;
            }
            logger.info("剩余："+ spiderInfo.getSize()+ " | buff"+ infoElement);
//            System.out.println("剩余："+ spiderInfo.getSize()+ " | buff"+ infoElement);
            for (String rarity : spiderInfo.getRarity().keySet()) {
                List<SellingBuyInfo> ls = getItem(rarity, hero, type);
//                System.out.println(ls);

                for (SellingBuyInfo info : ls) {
                    updateDB(info);
                }
            }
        }
    }


    private void updateDB(SellingBuyInfo sellingInfo) {
//        System.out.println(sellingInfo);
        if(mode == SpiderMode.NEWTABLE) {
//            if (buffService.isSellingExist(sellingInfo)) {
//                buffTable.updateSellingBuy(sellingInfo);
//            } else {
//                buffTable.inserSellingBuy(sellingInfo);
//            }
            buffService.addItemFullPro(sellingInfo);
        }
        else{
            buffService.addItemFull(sellingInfo);
        }

        buffService.addInfo(sellingInfo.getInfo());
    }

    public void test(){
        int i = 0;
        while (true) {
            buffUser.open(new HttpGet("https://buff.163.com/api/market/goods?game=dota2&page_num="+i+"&hero=npc_dota_hero_pugna&rarity=uncommon&type"));
            System.out.println(i++);
        }
    }

    @Override
    public List<SellingBuyInfo> getItem(String rarity, String hero, String type) {
        int page = 1;
        int maxPage = 2;
        List<SellingBuyInfo> list = new ArrayList<>();
        while (true) {
            try {
                if(page>maxPage) // 判断循环跳出
                {
                    break;
                }
//                System.out.println(String.format("第%d页",page));
                URIBuilder uriBuilder = new URIBuilder("https://buff.163.com/api/market/goods");
                // 设置请求参数
                uriBuilder.setParameter("game", "dota2");
                uriBuilder.setParameter("page_num", String.valueOf(page));
                uriBuilder.setParameter("hero", hero);
                uriBuilder.setParameter("rarity", rarity);
                uriBuilder.setParameter("type", type);
                uriBuilder.setParameter("page_size", 500+"");
                // 创建httpGet请求
                HttpGet httpGet = new HttpGet(uriBuilder.build());
                logger.debug(httpGet);
                String jsonText = "";
                int error = 0;
                try {
                     jsonText = buffUser.open(httpGet, useProxy, proxy);
                }
                catch (NetworkException e){
                    logger.error(e);
                    try {
                        Thread.sleep(1000*++error);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    continue;
                }
                if (jsonText == null) {
                    continue;
                }
                JSONObject json = JSON.parseObject(jsonText);
                if (!json.getString("code").equals("OK")) // 判断网页是否正常打开
                {
                    break;
                }
                JSONArray items = json.getJSONObject("data").getJSONArray("items");
                maxPage = json.getJSONObject("data").getInteger("total_page"); // 获取最大页数
                page++;
                for(int i=0;i<items.size();i++){ // 遍历每一个item，并获取必要信息
                    JSONObject item = items.getJSONObject(i);
                    String qname = item.getString("name");
                    QualityName qualityName = Tools.getQualityName(qname);
                    String name = qualityName.getName();
                    String id = item.getString("id");
                    String quality = qualityName.getQuality();
                    String steamName = item.getString("market_hash_name");
                    String heroName = hero==null?spiderInfo.getTypeCN(type):spiderInfo.getHeroCN(hero);
                    String rarityName = item.getJSONObject("goods_info").getJSONObject("info").getJSONObject("tags").getJSONObject("rarity").getString("localized_name");
                    int sellNum = item.getInteger("sell_num");
                    double sellPrice = item.getDouble("sell_min_price");
                    int buyNum = item.getInteger("buy_num");
                    double buyPrice = item.getDouble("buy_max_price");
                    ItemInfo itemInfo = new ItemInfo(id, new QualityName(quality ,name), rarityName, heroName, steamName , Platform.BUFF);
                    list.add(new SellingBuyInfo(itemInfo, buyPrice, buyNum, sellPrice, sellNum));
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        return list;
    }

    @Override
    public void run() {
        startSpider();
    }

}
